package com.linguochao.rabbitmq.config;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author linguochao
 * @Description RabbitMq获取队列消息数量
 * @Date 2020/7/27 14:39
 */
@Component
@Slf4j
public class RabbitMqUtils {

    @Resource
    RabbitAdmin rabbitAdmin;

    /**
     * 获取对应队列的数量;
     *
     * @param queue
     * @return
     */
    public int getQueueMessageCount(String queue) {
        int count=0;
        try {
            AMQP.Queue.DeclareOk declareOk = rabbitAdmin.getRabbitTemplate().execute(new ChannelCallback<AMQP.Queue.DeclareOk>() {
                @Override
                public AMQP.Queue.DeclareOk doInRabbit(Channel channel) throws Exception {
                    return channel.queueDeclarePassive(queue);
                }
            });
            count = declareOk.getMessageCount();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

}
